'use strict'

import {app, BrowserWindow, ipcMain, Menu, Tray} from 'electron'
import { initAutoUpdaterHandle, upgradeAutoUpdaterHandle } from './upgrade'
import GlobalSettings from './globalSettings'
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
const globalSettings = new GlobalSettings(process.env.NODE_ENV === 'development')
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
// tray变量
let appTray = null
let flashTrayTimer = null
let mainWindow
let expressServer
const winURL = globalSettings.isDevelopment
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
      devTools: globalSettings.isDevelopment,
      nodeIntegration: true, // 在网页中集成Node
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('close', (event) => {
    if (globalSettings.willQuitApp) {
      if (expressServer != null) {
        expressServer.close()
        expressServer = null
      }
    } else {
      mainWindow.hide()
      mainWindow.setSkipTaskbar(true)
      event.preventDefault()
    }
  })
}
// tray implementation function
function createTray () {
  // trayClose = false;
  const iconPath = `${__static}/tray.png`
  const trayContextMenu = Menu.buildFromTemplate([
    {
      label: '关闭',
      click () {
        // trayClose = true;
        // app.exit(1)
        // appTray = null
        app.quit()
        app.quit()
      }
    }
  ])
  appTray = new Tray(iconPath)
  appTray.setToolTip('xxxx客户端')
  appTray.setContextMenu(trayContextMenu)

  appTray.on('click', () => {
    if (flashTrayTimer != null) {
      clearInterval(flashTrayTimer)
      flashTrayTimer = null
      appTray.setImage(iconPath)
    }
    mainWindow.setSkipTaskbar(false)
    if (mainWindow.isMinimized()) {
      mainWindow.restore()
    } else {
      mainWindow.show()
    }
  })
}
// electron单实例启动
const shouldQuit = app.requestSingleInstanceLock()
if (!shouldQuit) {
  app.quit()
} else if (mainWindow) {
  mainWindow.setSkipTaskbar(false)
  if (mainWindow.isMinimized()) {
    mainWindow.restore()
  } else {
    mainWindow.show()
  }
} else {
  app.on('ready', () => {
    createWindow()
    if (process.platform !== 'darwin') {
      createTray()
    }
  })
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
      appTray = null
    }
  })
  app.on('activate', () => {
    if (mainWindow === null) {
      createWindow()
    } else {
      mainWindow.show()
    }
  })
  app.on('before-quit', () => {
    globalSettings.willQuitApp = true
  })
  ipcMain.on('systemExit', () => {
    app.exit(1)
    appTray = null
  })
  // 忽略证书相关错误, 非认证证书
  app.commandLine.appendSwitch('ignore-certificate-errors')
}
ipcMain.on('loginSuccess', (event, data) => {
  const feedUrl = `http://localhost:8000/download/win/`
  if (!globalSettings.uploaderInited) {
    initAutoUpdaterHandle(mainWindow, globalSettings, feedUrl)
    globalSettings.uploaderInited = true
  } else {
    upgradeAutoUpdaterHandle(feedUrl)
  }
})
